package com.coszero.utils.media

import android.content.Context
import android.media.MediaPlayer
import android.util.Log

/**
 * Desc： 音频播放工具类
 * 播放音频时有一定延迟,实时读较高的建议使用SoundPool
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/9/3 0003 13:49
 *
 *
 * MediaPlayerUtils.playAdudio(mActivity, R.raw.serror);
 * @version 1
 */
object MediaPlayerUtils {
    var mMediaPlayer: MediaPlayer? = null


    val mediaPlayer: MediaPlayer
        get() {
            if (null == mMediaPlayer) {
                mMediaPlayer = MediaPlayer()
            }

            return mMediaPlayer!!
        }


    /**
     * 播放音频
     */
    fun playAudio(mContext: Context, fileName: String) {
        try {
            stopAudio() //如果正在播放就停止
            val assetManager = mContext.assets
            val afd = assetManager.openFd(fileName)
            val mediaPlayer =
                mediaPlayer
            mediaPlayer.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
            mediaPlayer.isLooping = false //循环播放
            mediaPlayer.prepare()
            mediaPlayer.setOnPreparedListener { mediaPlayer -> mediaPlayer.start() }
        } catch (e: Exception) {
            Log.e("播放音频失败", "")
        }
    }

    fun playAdudio(mContext: Context?, rawId: Int) {
        if (null != mMediaPlayer) {
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.pause()
            }
            mMediaPlayer!!.release()
        }
        mMediaPlayer = MediaPlayer.create(mContext, rawId)
        mMediaPlayer.start()
    }


    /**
     * 停止播放音频
     */
    fun stopAudio() {
        try {
            if (null != mMediaPlayer) {
                if (mMediaPlayer!!.isPlaying) {
                    mMediaPlayer!!.pause()
                    mMediaPlayer!!.reset()
                    mMediaPlayer!!.stop()
                }
            }
        } catch (e: Exception) {
            Log.e("stopAudio", e.message!!)
        }
    }
}
